package com.fi.recogn.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author XianLei
 * @Desc
 * @Date 2023/06/06 18:33:27
 */
@Slf4j
public class MD5Utils {
    static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    static final char hexDigitsLower[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 对字符串 MD5 无盐值加密
     *
     * @param plainText 传入要加密的字符串
     * @return MD5加密后生成32位(小写字母 + 数字)字符串
     */
    public static String MD5Lower(String plainText) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            md.update(plainText.getBytes());

            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值。1 固定值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 对字符串 MD5 加密
     *
     * @param plainText 传入要加密的字符串
     * @return MD5加密后生成32位(大写字母 + 数字)字符串
     */
    public static String MD5Upper(String plainText) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            md.update(plainText.getBytes());

            // 获得密文
            byte[] mdResult = md.digest();
            // 把密文转换成十六进制的字符串形式
            int j = mdResult.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = mdResult[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换, >>> 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对字符串 MD5 加盐值加密
     *
     * @param plainText 传入要加密的字符串
     * @param saltValue 传入要加的盐值
     * @return MD5加密后生成32位(小写字母 + 数字)字符串
     */
    public static String MD5Lower(String plainText, String saltValue) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            md.update(plainText.getBytes());
            md.update(saltValue.getBytes());

            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值。1 固定值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对字符串 MD5 加盐值加密
     *
     * @param plainText 传入要加密的字符串
     * @param saltValue 传入要加的盐值
     * @return MD5加密后生成32位(大写字母 + 数字)字符串
     */
    public static String MD5Upper(String plainText, String saltValue) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            md.update(plainText.getBytes());
            md.update(saltValue.getBytes());

            // 获得密文
            byte[] mdResult = md.digest();
            // 把密文转换成十六进制的字符串形式
            int j = mdResult.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = mdResult[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * MD5加密后生成32位(小写字母+数字)字符串
     * 同 MD5Lower() 一样
     */
    public final static String MD5(String plainText) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");

            mdTemp.update(plainText.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigitsLower[byte0 >>> 4 & 0xf];
                str[k++] = hexDigitsLower[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * String -> MD5
     */
    public static String getMD5(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(val.getBytes());
        byte[] m = md5.digest();// 加密
        return getString(m);
    }

    // bArray -> String
    private static String getString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            hexString.append(Integer.toHexString(0xFF & b[i]));
        return hexString.toString();
    }

    /**
     * 校验MD5码
     *
     * @param text 要校验的字符串
     * @param md5  md5值
     * @return 校验结果
     */
    public static boolean valid(String text, String md5) {
        return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase());
    }


    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        long time = 1686047800014L;
        System.out.println(System.currentTimeMillis());
        String plainText = "-" + time;
        String saltValue = "admin123";
//07cc694b9b3fc636710fa08b6922c42b
//        System.out.println(MD5Lower(plainText));
//        System.out.println(MD5Upper(plainText));
//        System.out.println(MD5Lower(plainText, saltValue));
//        System.out.println(MD5Upper(plainText, saltValue));
        System.out.println(MD5(plainText));
        System.out.println("=====校验结果======");
        System.out.println(valid(plainText, MD5(plainText)));

//
//        String url = "https://api.banklaw.com/nlp/algorithms/v1/gpt/edit/msg";
//        Map<String, Object> param = new HashMap<>();
//        param.put("async", false);
//        param.put("chatSessionId", 43);
//        param.put("content", sendMsg);
//        String postForJson = AlgorithmsHttpRequestUtil.sendPostForJson(url, JSONObject.toJSONString(param), 600000);
//        JSONObject jsonObject = JSONObject.parseObject(postForJson);
//        JSONObject data = (JSONObject) jsonObject.get("data");
//        String resContent = (String) data.get("content");
//        int index = resContent.lastIndexOf("公告标题");
//        if (index > -1) {
//            String matchTitle = resContent.substring(index + 5);
//        }

    }

    public static String sendPostForJson(String url, String param) throws Exception {
        return sendPostForJson(url, param, (Integer) null);
    }

    public static String sendPostForJson(String url, String param, Integer readTimeOut) throws Exception {
        return sendPostForJson(url, param, readTimeOut, (Map) null);
    }

    public static String sendPutForJson(String url, String param, Integer readTimeOut) throws Exception {
        return sendPutForJson(url, param, readTimeOut, (Map) null);
    }

    public static String sendPutForJson(String url, String param, Integer readTimeOut, Map<String, String> heardInfo) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            long time = System.currentTimeMillis();
            String plainText = "-" + time;
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Access-Time", time + "");
            conn.setRequestProperty("Access-Signature", MD5(plainText));
            conn.setRequestProperty("Accept", "application/json, text/plain, */*");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");
            conn.setConnectTimeout(20000);
            if (heardInfo != null) {
                Iterator var9 = heardInfo.entrySet().iterator();

                while (var9.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry) var9.next();
                    conn.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
                }
            }

            if (readTimeOut == null || readTimeOut <= 0) {
                readTimeOut = 40000;
            }

            conn.setReadTimeout(readTimeOut);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            int responseCode = httpURLConnection.getResponseCode();
            if (404 == responseCode) {
                throw new RuntimeException("请求404");
            }

            String line;
            for (in = new BufferedReader(new InputStreamReader(conn.getInputStream())); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var19) {
            throw var19;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var18) {
                var18.printStackTrace();
            }

        }

        return result;
    }

    public static String sendPostForJson(String url, String param, Integer readTimeOut, Map<String, String> heardInfo) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            long time = System.currentTimeMillis();
            String plainText = "-" + time;
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Access-Time", time + "");
            conn.setRequestProperty("Access-Signature", MD5(plainText));
            conn.setRequestProperty("Accept", "application/json, text/plain, */*");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");
            conn.setConnectTimeout(20000);
            if (heardInfo != null) {
                Iterator var9 = heardInfo.entrySet().iterator();

                while (var9.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry) var9.next();
                    conn.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
                }
            }

            if (readTimeOut == null || readTimeOut <= 0) {
                readTimeOut = 40000;
            }

            conn.setReadTimeout(readTimeOut);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            int responseCode = httpURLConnection.getResponseCode();
            if (404 == responseCode) {
                throw new RuntimeException("请求404超时");
            }

            String line;
            for (in = new BufferedReader(new InputStreamReader(conn.getInputStream())); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var19) {
            throw var19;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var18) {
                var18.printStackTrace();
            }

        }
        return result;
    }
}
